import os
import platform
import time

from PyQt6.QtCore import QRect, QSize, Qt, QThreadPool
from PyQt6.QtGui import QImage, QPixmap, QFont, QIcon
from PyQt6.QtWidgets import QListWidget, QListWidgetItem, QScrollArea, QHBoxLayout, QVBoxLayout, QLabel, \
    QWidget, QCheckBox, QSizePolicy, QGridLayout, QTextEdit, QPushButton, QSpacerItem

import global_config
from scripts import db_utils
from scripts.WorkSingle import Worker
from scripts.beans import Storyboard
from ui.widgets.ClickableLabel import ClickableLabel
from ui.widgets.CustomWidgets import MyCheckBox
from ui.widgets.Image_dialog import ConfirmDialog


class AdapterItem():

    def setSelected(self, select):
        self.index_checkbox.setChecked(select)

    def __init__(self, itemwidget, index, bean: Storyboard, callback):
        super().__init__()
        self.index = index
        self.callback = callback
        self.itemwidget = itemwidget
        self.bean = bean
        self.images_widget: QWidget = None
        self.promots_tv :QTextEdit= None
        self.videoholder = None
        self.itemview: QHBoxLayout = None
        self.initView(index, itemwidget)

    def initView(self, index, itemwidget):
        itemwidget.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)

        self.itemview = QHBoxLayout()
        self.itemview.setSpacing(4)
        self.itemview.setContentsMargins(2, 2, 2, 2)
        itemwidget.setLayout(self.itemview)

        # index
        self.index_checkbox = MyCheckBox(str(index))
        self.add_itemView(self.index_checkbox, self.itemview, 1, QSizePolicy.Policy.Fixed)

        # 字幕
        self.srtview = QWidget()
        self.srtlayout = QVBoxLayout()
        self.srtlayout.setContentsMargins(2, 2, 2, 2)
        self.srtview.setLayout(self.srtlayout)
        self.srtlayout.setSpacing(4)
        self.add_itemView(self.srtview, self.itemview, 1, QSizePolicy.Policy.Fixed)
        for srt in self.bean.srtbean:
            srt_tv = QLabel()
            font = QFont('Arial', 11, 100)
            srt_tv.setText(srt['text'] if srt['text'] is not None else "无字幕")
            srt_tv.setWordWrap(True)
            srt_tv.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
            srt_tv.setFont(font)
            self.srtlayout.addWidget(srt_tv)
        spaser = QSpacerItem(20, 20, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding)
        self.srtlayout.addItem(spaser)

        # 时间轴
        # time_tv = QLabel(f"开始：{self.bean.start}\n结束：{self.bean.end}")
        # self.add_itemView(time_tv, self.itemview, 1, QSizePolicy.Policy.Minimum, 100)

        # key_frame
        if self.bean.local_img is not None:
            frame_tv = QLabel()
            pixmap = QPixmap(self.bean.local_img)
            pixmap = pixmap.scaled(QSize(100, 100), Qt.AspectRatioMode.KeepAspectRatioByExpanding)
            frame_tv.setPixmap(pixmap)
            self.add_itemView(frame_tv, self.itemview, 1, QSizePolicy.Policy.Minimum, 100)

        # promots
        self.promots_tv = QTextEdit(self.bean.promots)
        font = QFont()
        font.setPointSize(16)
        self.promots_tv.document().setDefaultFont(font)

        def ontextchaged():
            self.bean.promots = self.promots_tv.toPlainText()

        self.promots_tv.textChanged.connect(ontextchaged)
        self.add_itemView(self.promots_tv, self.itemview, 1, QSizePolicy.Policy.Minimum, 100)

        # # suffix
        # suffix_tv = QTextEdit(self.bean.suffix)
        # suffix_tv.setPlaceholderText('后缀')
        # font = QFont()
        # font.setPointSize(16)
        # suffix_tv.document().setDefaultFont(font)
        #
        # def ontextchaged():
        #     self.bean.suffix = suffix_tv.toPlainText()
        #
        # suffix_tv.textChanged.connect(ontextchaged)
        # self.add_itemView(suffix_tv, self.itemview, 0, QSizePolicy.Policy.Fixed, 40, 100)

        # 推理按钮
        reasoning_btn = QPushButton('推理')
        reasoning_btn.clicked.connect(lambda: self.callback('推理', self.index))
        reasoning_btn.setStyleSheet("background-color: rgba(255, 0, 0, 128); color:white")
        self.add_itemView(reasoning_btn, self.itemview, 0, QSizePolicy.Policy.Fixed, 40, 40)


        # download images
        self.update_imagesUI()


    def update_imagesUI(self):
        if self.images_widget is not None:
            for v in self.images_widget.findChildren(QWidget,'inner_view')+self.images_widget.findChildren(ClickableLabel,'img_iv'):
                self.images_widget.layout().removeWidget(v)
                v.deleteLater()
        else:
            self.images_widget = QWidget()
            outlayout = QHBoxLayout()
            outlayout.setContentsMargins(0,0,0,0)
            outlayout.setSpacing(0)
            self.images_widget.setLayout(outlayout)
            self.add_itemView(self.images_widget, self.itemview, 0, QSizePolicy.Policy.Fixed, 400, 390)

        self.show_selected_img(self.bean.select_img, self.images_widget)
        self.show_image_results(self.images_widget)
        self.promots_tv.setText(self.bean.promots)



    def add_itemView(self, view: QWidget, parent, factor, policy=QSizePolicy.Policy.Expanding, width=40, max_w=-1):
        view.setMinimumHeight(40)
        view.setMinimumWidth(width)
        view.setContentsMargins(0, 0, 0, 0)
        if max_w != -1:
            view.setMaximumWidth(max_w)
        # view.setStyleSheet("background-color: rgba(255, 255, 255, 255)")
        view.setSizePolicy(policy, QSizePolicy.Policy.Expanding)
        parent.addWidget(view, factor)

    # ai图 结果展示容器
    def show_selected_img(self, path, out_widget):
        imageholder = ImagesHolder(self,path, out_widget.layout(), True)
        imageholder.img_iv.setFixedSize(QSize(200, 200))
        out_widget.layout().addWidget(imageholder.img_iv)
        imageholder.setimage()

    # ai图 结果展示容器
    def show_image_results(self, out_widget):
        images_widget = QWidget()
        images_widget.setObjectName('inner_view')
        layout = QGridLayout()
        layout.setSpacing(5)
        layout.setContentsMargins(5, 0, 0, 0)
        images_widget.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)

        images_widget.setLayout(layout)
        out_widget.layout().addWidget(images_widget)

        aiImgDir = f'{global_config.get_workflows_img_dir()}\\{self.index}\\'
        if not os.path.exists(aiImgDir):
            os.makedirs(aiImgDir)
        filelist = os.listdir(aiImgDir)
        for index in range(0, 4):
            revers_index = len(filelist) - 1 - index
            path = f'{aiImgDir}{filelist[revers_index]}' if revers_index >= 0 and revers_index < len(
                filelist) else ''
            # print(path)
            imageholder = ImagesHolder(self, path, layout, False)
            row = index % 2
            column = int(index / 2)
            imageholder.img_iv.setText(f"{row},{column},{index},{path}")
            imageholder.img_iv.setFixedSize(QSize(90, 97))
            layout.addWidget(imageholder.img_iv, row, column, 1, 1)
            imageholder.setimage()

class ImagesHolder():
    img_iv: ClickableLabel = None

    def __init__(self, adapteritem:AdapterItem, path, layout,isBig= False):
        self.path = path
        self.layout: QGridLayout = layout
        self.img_iv = ClickableLabel(self.path)
        self.img_iv.setObjectName('img_iv')
        self.adapteritem = adapteritem
        def innerclick():
            if self.path is not None and os.path.exists(self.path):
                if isBig :
                        ConfirmDialog(self.path, self.ondelete).get_result()
                else:
                    adapteritem.bean.select_img = self.path
                    adapteritem.update_imagesUI()

        self.img_iv.clicked.connect(innerclick)

    def ondelete(self):
        # 自动选中第一个图片
        if self.adapteritem.bean.select_img is None or not os.path.exists(self.adapteritem.bean.select_img):
            aiImgDir = f'{global_config.get_workflows_img_dir()}\\{self.adapteritem.index}\\'
            if os.path.exists(aiImgDir):
                filelist = os.listdir(aiImgDir)
                self.adapteritem.bean.select_img = f'{aiImgDir}{filelist[0]}' if len(filelist) > 0 else None
        self.adapteritem.update_imagesUI()


    def setimage(self):
        photo = QPixmap(self.path)
        photo = photo.scaled(QSize(200, 200), Qt.AspectRatioMode.IgnoreAspectRatio)
        self.img_iv.setPixmap(photo)


class VideoHolder():
    view: QPushButton = None

    def __init__(self, path):
        self.path = path

        self.view = QPushButton("视频目录")

        def innerclick():
            if os.path.exists(self.path):
                if platform.system() == 'Darwin':
                    os.system(f'open /{self.path}')
                else:
                    os.startfile(self.path)

        self.view.clicked.connect(innerclick)
